package com.netease.nim.uikit.business.session.module.list;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.business.session.activity.P2PMessageActivity;
import com.netease.nim.uikit.business.session.activity.ProviderUser;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.business.session.module.Container;
import com.netease.nim.uikit.business.session.viewholder.MsgViewHolderBase;
import com.netease.nim.uikit.business.session.viewholder.MsgViewHolderFactory;
import com.netease.nim.uikit.business.team.model.UserInfo;
import com.netease.nim.uikit.common.ui.recyclerview.adapter.BaseMultiItemFetchLoadAdapter;
import com.netease.nim.uikit.common.ui.recyclerview.holder.BaseViewHolder;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by huangjun on 2016/12/21.
 */
public class MsgAdapter extends BaseMultiItemFetchLoadAdapter<IMMessage, BaseViewHolder> {
    public UserInfo getUserInfoFromDb(Context context) {
        if (context == null) return null;
        UserInfo user = new UserInfo();
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(ProviderUser.User.CONTENT_URI, null
                    , null, null, null);
            if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
                String data = cursor.getString(cursor.getColumnIndex(ProviderUser.User.DATA));
                if (!TextUtils.isEmpty(data)) {
                    user = new Gson().fromJson(data, UserInfo.class);
                    return user;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) cursor.close();
        }
        return user;
    }

    private Map<Class<? extends MsgViewHolderBase>, Integer> holder2ViewType;

    private ViewHolderEventListener eventListener;
    private Map<String, Float> progresses; // 有文件传输，需要显示进度条的消息ID map
    private String messageId;
    private Container container;
    MsgAdapter(RecyclerView recyclerView, List<IMMessage> data, Container container) {
        super(recyclerView, data);
        timedItems = new HashSet<>();
        progresses = new HashMap<>();
        // view type, view holder
        holder2ViewType = new HashMap<>();
        List<Class<? extends MsgViewHolderBase>> holders = MsgViewHolderFactory.getAllViewHolders();
        int viewType = 0;
        for (Class<? extends MsgViewHolderBase> holder : holders) {
            viewType++;
            addItemType(viewType, R.layout.nim_message_item, holder);
            holder2ViewType.put(holder, viewType);
        }
        this.container = container;


//        registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
//            @Override
//            public void onChanged() {
//                Log.e("TAG","AdapterData Change....");
//            }
//        });
    }
    private IMMessage imMessage;
    private String type,userId;
    public void setType(String type,String userId){
        this.type=type;
        this.userId=userId;
    }

    @Override
    public void setLayout(LinearLayout bottom, RelativeLayout top, final IMMessage message, final LinearLayout bottom_bot, final int position, TextView config, TextView exit, final RatingBar ratingBar,TextView content,View view_line,TextView title){
        if(message.getContent()!=null&&((message.getContent().equals("咨询已结束，请评价"))||(message.getContent().contains("分配到您的名下")))){
            top.setVisibility(View.GONE);
            bottom.setVisibility(View.VISIBLE);
        }else {
            bottom.setVisibility(View.GONE);
            top.setVisibility(View.VISIBLE);
        }
        if(message.getRemoteExtension()!=null&&message.getRemoteExtension().get("messageType")!=null&&(message.getRemoteExtension().get("messageType").equals("1")||message.getRemoteExtension().get("messageType").equals("2"))){
            ratingBar.setVisibility(View.VISIBLE);
            view_line.setVisibility(View.VISIBLE);
            bottom_bot.setVisibility(View.GONE);
            bottom.setVisibility(View.VISIBLE);
            top.setVisibility(View.GONE);
            exit.setVisibility(View.VISIBLE);
            config.setVisibility(View.VISIBLE);
            title.setText("服务打星");
            config.setText("确认");
            if(message.getRemoteExtension().get("messagePosition")!=null){
                ratingBar.setRating(Float.valueOf(message.getRemoteExtension().get("messagePosition").toString()));
            }
            ratingBar.setIsIndicator(true);
            content.setText("感谢您为本次服务打星，祝您身体健康");
        }else if(message.getRemoteExtension()!=null&&message.getRemoteExtension().get("messageType")!=null&&(message.getRemoteExtension().get("messageType").equals("0"))){
            top.setVisibility(View.GONE);
            exit.setVisibility(View.VISIBLE);
            bottom.setVisibility(View.VISIBLE);
            title.setText("服务打星");
            view_line.setVisibility(View.VISIBLE);
            bottom_bot.setVisibility(View.VISIBLE);
            config.setVisibility(View.VISIBLE);
            config.setText("确认");
            if(message.getRemoteExtension().get("messagePosition")!=null){
                ratingBar.setRating(Float.valueOf(message.getRemoteExtension().get("messagePosition").toString()));
            }
            content.setText("请您为本次服务打星，祝您身体健康");
            if(type!=null&&type!=null&&type.equals("2")){
                bottom_bot.setVisibility(View.GONE);
                ratingBar.setIsIndicator(true);
            }else {
                ratingBar.setIsIndicator(false);
            }
            ratingBar.setVisibility(View.VISIBLE);
        }else if(message.getRemoteExtension()!=null&&message.getRemoteExtension().get("messageType")!=null&&(message.getRemoteExtension().get("messageType").equals("3"))){
            ratingBar.setVisibility(View.GONE);
            exit.setVisibility(View.GONE);
            top.setVisibility(View.GONE);
            bottom.setVisibility(View.VISIBLE);

            title.setText("用户分配");
            view_line.setVisibility(View.GONE);
            if(message.getRemoteExtension().get("userNickName")!=null){
                content.setText("已将"+message.getRemoteExtension().get("userNickName")+"分配到您的名下");
            }else {
                content.setText("已将xx分配到您的名下");
            }
            config.setText("点击与其进行咨询");
            if(message.getRemoteExtension()==null||message.getRemoteExtension().get("fromUserId")==null){
                Toast.makeText(mContext,"请传入被分配的咨询师id",Toast.LENGTH_LONG).show();
                config.setVisibility(View.GONE);
                return;
            }
            if(message.getRemoteExtension()!=null&&message.getRemoteExtension().get("fromUserId")!=null&&message.getRemoteExtension().get("fromUserId").equals(userId)){
                config.setVisibility(View.VISIBLE);
            }else {
                config.setVisibility(View.GONE);
            }

        }else {
            ratingBar.setVisibility(View.VISIBLE);
            bottom.setVisibility(View.GONE);
            top.setVisibility(View.VISIBLE);
            exit.setVisibility(View.VISIBLE);
            ratingBar.setIsIndicator(false);
            title.setText("服务打星");
            view_line.setVisibility(View.VISIBLE);
            config.setVisibility(View.VISIBLE);
            config.setText("确认");
            content.setText("感谢您为本次服务打星，祝您身体健康");
        }
        config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(message.getRemoteExtension()!=null&&message.getRemoteExtension().get("messageType")!=null&&(message.getRemoteExtension().get("messageType").equals("3"))){
                    onChatCommentClickLinstener.onConfigClick(message, (int) ratingBar.getRating());
                    return;
                }
                if((int)ratingBar.getRating()==0){
                    Toast.makeText(mContext,"请至少选择一星",Toast.LENGTH_LONG).show();
                    return;
                }
                bottom_bot.setVisibility(View.GONE);
                if(onChatCommentClickLinstener!=null){
                    onChatCommentClickLinstener.onConfigClick(message, (int) ratingBar.getRating());
                }

            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottom_bot.setVisibility(View.GONE);
                if(onChatCommentClickLinstener!=null){
                    onChatCommentClickLinstener.onExitCancle(message,(int) ratingBar.getRating());
                }

            }
        });

    }
    public OnChatCommentClickLinstener onChatCommentClickLinstener;
    public interface OnChatCommentClickLinstener{
        void onConfigClick(IMMessage message,int position);
        void onExitCancle(IMMessage message,int position);
    }
    public void setOnChatCommentClickLinstener(OnChatCommentClickLinstener onChatCommentClickLinstener){
        this.onChatCommentClickLinstener=onChatCommentClickLinstener;

    }

    @Override
    protected int getViewType(IMMessage message) {
        return holder2ViewType.get(MsgViewHolderFactory.getViewHolderByType(message));
    }

    @Override
    protected String getItemKey(IMMessage item) {
        return item.getUuid();
    }

    public void setEventListener(ViewHolderEventListener eventListener) {
        this.eventListener = eventListener;
    }

    public ViewHolderEventListener getEventListener() {
        return eventListener;
    }

    public void deleteItem(IMMessage message, boolean isRelocateTime) {
        if (message == null) {
            return;
        }

        int index = 0;
        for (IMMessage item : getData()) {
            if (item.isTheSame(message)) {
                break;
            }
            ++index;
        }

        if (index < getDataSize()) {
            remove(index);
            if (isRelocateTime) {
                relocateShowTimeItemAfterDelete(message, index);
            }
//            notifyDataSetChanged(); // 可以不要！！！
        }
    }

    public float getProgress(IMMessage message) {
        Float progress = progresses.get(message.getUuid());
        return progress == null ? 0 : progress;
    }

    public void putProgress(IMMessage message, float progress) {
        progresses.put(message.getUuid(), progress);
    }

    /**
     * *********************** 时间显示处理 ***********************
     */

    private Set<String> timedItems; // 需要显示消息时间的消息ID
    private IMMessage lastShowTimeItem; // 用于消息时间显示,判断和上条消息间的时间间隔

    public boolean needShowTime(IMMessage message) {
        return timedItems.contains(message.getUuid());
    }

    /**
     * 列表加入新消息时，更新时间显示
     */
    public void updateShowTimeItem(List<IMMessage> items, boolean fromStart, boolean update) {
        IMMessage anchor = fromStart ? null : lastShowTimeItem;
        for (IMMessage message : items) {
            if (setShowTimeFlag(message, anchor)) {
                anchor = message;
            }
        }

        if (update) {
            lastShowTimeItem = anchor;
        }
    }

    /**
     * 是否显示时间item
     */
    private boolean setShowTimeFlag(IMMessage message, IMMessage anchor) {
        boolean update = false;

        if (hideTimeAlways(message)) {
            setShowTime(message, false);
        } else {
            if (anchor == null) {
                setShowTime(message, true);
                update = true;
            } else {
                long time = anchor.getTime();
                long now = message.getTime();

                if (now - time == 0) {
                    // 消息撤回时使用
                    setShowTime(message, true);
                    lastShowTimeItem = message;
                    update = true;
                } else if (now - time < (NimUIKitImpl.getOptions().displayMsgTimeWithInterval)) {
                    setShowTime(message, false);
                } else {
                    setShowTime(message, true);
                    update = true;
                }
            }
        }

        return update;
    }

    private void setShowTime(IMMessage message, boolean show) {
        if (show) {
            timedItems.add(message.getUuid());
        } else {
            timedItems.remove(message.getUuid());
        }
    }

    private void relocateShowTimeItemAfterDelete(IMMessage messageItem, int index) {
        // 如果被删的项显示了时间，需要继承
        if (needShowTime(messageItem)) {
            setShowTime(messageItem, false);
            if (getDataSize() > 0) {
                IMMessage nextItem;
                if (index == getDataSize()) {
                    //删除的是最后一项
                    nextItem = getItem(index - 1);
                } else {
                    //删除的不是最后一项
                    nextItem = getItem(index);
                }

                // 增加其他不需要显示时间的消息类型判断
                if (hideTimeAlways(nextItem)) {
                    setShowTime(nextItem, false);
                    if (lastShowTimeItem != null && lastShowTimeItem != null
                            && lastShowTimeItem.isTheSame(messageItem)) {
                        lastShowTimeItem = null;
                        for (int i = getDataSize() - 1; i >= 0; i--) {
                            IMMessage item = getItem(i);
                            if (needShowTime(item)) {
                                lastShowTimeItem = item;
                                break;
                            }
                        }
                    }
                } else {
                    setShowTime(nextItem, true);
                    if (lastShowTimeItem == null
                            || (lastShowTimeItem != null && lastShowTimeItem.isTheSame(messageItem))) {
                        lastShowTimeItem = nextItem;
                    }
                }
            } else {
                lastShowTimeItem = null;
            }
        }
    }

    private boolean hideTimeAlways(IMMessage message) {
        if (message.getSessionType() == SessionTypeEnum.ChatRoom) {
            return true;
        }
        switch (message.getMsgType()) {
            case notification:
                return true;
            default:
                return false;
        }
    }

    public interface ViewHolderEventListener {
        // 长按事件响应处理
        boolean onViewHolderLongClick(View clickView, View viewHolderView, IMMessage item);

        // 发送失败或者多媒体文件下载失败指示按钮点击响应处理
        void onFailedBtnClick(IMMessage resendMessage);

        // viewholder footer按钮点击，如机器人继续会话
        void onFooterClick(IMMessage message);
    }

    public void setUuid(String messageId) {
        this.messageId = messageId;
    }

    public String getUuid() {
        return messageId;
    }

    public Container getContainer() {
        return container;
    }
}
